import 'dart:convert';
import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:management/app/api.dart';
import 'package:management/model/user_model.dart';
import 'package:management/utils/http_utils.dart';
import 'package:management/utils/log_utils.dart';

///登录
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  GlobalKey<FormState> _formKey = GlobalKey();
  TextEditingController _userNameController = TextEditingController();
  TextEditingController _pswController = TextEditingController();
  bool pwdShow = false; //密码是否显示明文

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "登录",
          style: TextStyle(fontSize: 25),
        ),
        centerTitle: true,
      ),
      body: Container(
        child: SingleChildScrollView(
          child: Center(
            child: Form(
              key: _formKey,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              onWillPop: () async {
                return await showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                          title: Text("提示"),
                          content: Text("确定要离开此页吗？"),
                          actions: [
                            TextButton(
                                onPressed: () {
                                  Navigator.of(context).pop(true);
                                },
                                child: Text("确定")),
                            TextButton(
                              onPressed: () {
                                Navigator.of(context).pop(false);
                              },
                              child: Text("取消"),
                            )
                          ],
                        ));
              },
              child: Column(
                children: [
                  Container(
                    height: 120,
                    child: TextFormField(
                      controller: _userNameController,
                      style: TextStyle(fontSize: 30),
                      decoration: InputDecoration(
                          prefixIcon: Icon(Icons.person),
                          labelText: "用户名",
                          hintText: "请输入用户名"),
                      validator: _validatorUserName,
                    ),
                  ),
                  Container(
                    height: 120,
                    child: TextFormField(
                      controller: _pswController,
                      style: TextStyle(fontSize: 30),
                      decoration: InputDecoration(
                        prefixIcon: Icon(Icons.lock),
                        labelText: "密码",
                        hintText: "请输入密码",
                        suffixIcon: Padding(
                          padding: EdgeInsets.only(right: 20),
                          child: IconButton(
                            icon: pwdShow
                                ? Icon(
                                    Icons.visibility,
                                    size: 30,
                                  )
                                : Icon(
                                    Icons.visibility_off,
                                    size: 35,
                                  ),
                            onPressed: () {
                              setState(() {
                                pwdShow = !pwdShow;
                              });
                            },
                          ),
                        ),
                      ),
                      obscureText: !pwdShow,
                      validator: _validatorPsw,
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TextButton(
                        onPressed: () {
                          _userLogin();
                        },
                        child: Text(
                          "登录",
                          style: TextStyle(fontSize: 30),
                        ),
                      ),
                      TextButton(
                        onPressed: () {
                          _userRegister();
                        },
                        child: Text(
                          "注册",
                          style: TextStyle(fontSize: 30),
                        ),
                      ),
                      // TextButton(
                      //   onPressed: () {
                      //     Fluttertoast.showToast(msg: "忘记密码");
                      //   },
                      //   child: Text("忘记密码"),
                      // ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  void _userLogin() async {
    _formKey.currentState!.save();
    if (_formKey.currentState!.validate()) {
      String userName = _userNameController.text;
      String userPsw = _pswController.text;
      //数据库查询 是否存在这个账号
      User? user = await UserProvider.instance.queryName(userName);
      LoginState loginState;
      if (user == null) {
        loginState = LoginState("用户不存在", false);
      } else {
        loginState = await user.login(
          user,
          name: userName,
          psw: userPsw,
        );
      }

      if (loginState.isOk) {
        SpUtil.putString("userName", user!.name!);
        Navigator.of(context).pop();
        Navigator.of(context).pushNamed('/HomePage');
        loginFaceCloud(user);
        ParkApi.loginParkCloud();
      } else {
        Fluttertoast.showToast(msg: loginState.msg);
      }
    }
  }

  void _userRegister() {
    // Fluttertoast.showToast(msg: "注册");
    Navigator.of(context).pushNamed('/RegisterPage');
  }

  String? _validatorUserName(String? value) {
    if (value!.isEmpty) {
      return "用户名不能为空";
    }
    return null;
  }

  String? _validatorPsw(String? value) {
    if (value!.isEmpty) {
      return "密码不能为空";
    }
    return null;
  }

  ///登录人脸云
  void loginFaceCloud(User user) async {
    MyLog.w("${user.faceToken}");
    HttpUtil.post(
        url: FaceApi.face_url_login,
        body: {"userName": "face_hj", "userPassword": "123_cy"},
        onSuccess: (message) {
          MyLog.i("人脸云登录成功 message: $message");
          //保存token
          FaceApi.faceToken = JsonDecoder().convert(message.toString())["data"]["token"];
          UserProvider.instance.update(
            user,
            User(
              user.name,
              user.psw,
              faceToken: FaceApi.faceToken,
            ),
          );
        },
        onFail: (stateCode, message) {
          MyLog.e("""人脸云登录失败 statusCode: $stateCode \n message: $message""");
          Fluttertoast.showToast(msg: message.toString());
        });
  }

  ///登录车场云
  void loginParkCloud() async {
    var response = await HttpUtil.client.post(
      Uri.parse(ParkApi.park_host + ParkApi.url_login),
      headers: const {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JsonUtil.encodeObj(ParkApi.park_loginBody),
    );

    if (response.statusCode == HttpStatus.ok) {}

    MyLog.d("loginParkCloud response: ${response.body}");
  }
}
